<template>
  <div>
    <form action="/">
      <van-search
        v-model="keywords"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        background="#e95363"
        class="search-inp"
        @focus="isShowResult = false"
      />
    </form>
    <!-- 搜索历史/建议/结果 -->
    <!-- <search-history></search-history>
    <search-result></search-result>
    <search-suggestions></search-suggestions> -->
    <component
      :is="componentName"
      :keywords="keywords"
      @update_kws="onSearch"
    />
  </div>
</template>

<script>
import SearchHistory from '@/views/Search/components/SearchHistory'
import SearchResult from '@/views/Search/components/SearchResult'
import SearchSuggestions from '@/views/Search/components/SearchSuggestions'
import { mapMutations, mapState } from 'vuex'
export default {
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggestions
  },
  data() {
    return {
      keywords: '',
      isShowResult: false //记录是否触发了搜索事件
    }
  },
  computed: {
    ...mapState(['histories']),
    componentName() {
      //搜索框没有实际内容的时候渲染搜索历史
      if (this.keywords.trim() === '') return 'SearchHistory'
      if (this.isShowResult) return 'SearchResult'
      //逻辑走到最后只可能是渲染搜索建议
      return 'SearchSuggestions'
    }
  },
  methods: {
    ...mapMutations(['SET_HISTORIES']),
    onSearch(val) {
      // 1\更新keywords
      this.keywords = val
      // 2\存到本地
      let newHistories = [this.keywords, ...this.histories]
      // 3\去重
      newHistories = [...new Set(newHistories)]
      this.SET_HISTORIES(newHistories)
      // 4|触发了搜索事件
      this.isShowResult = true
    },
    onCancel() {
      // 触发取消，先清空keywords，再触发onCancel
      if (this.keywords === '') {
        this.$router.go(-1)
        // this.keywords = ''
      } else {
        this.keywords = ''
        // this.$router.go(-1)
      }
    }
  }
}
</script>

<style scoped lang="less">
.search-inp {
  .van-search__action {
    color: #fff;
  }
}
</style>
